import 'dart:async';
import 'dart:io';

import 'package:base_flutter/base_flutter.dart';
import 'package:environment_sensors/environment_sensors.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:ls_work/config/permission_center_config.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:permission_handler/permission_handler.dart';



class ScanQrPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _ScanQrState();
}

class _ScanQrState extends State<ScanQrPage> with WidgetsBindingObserver{
  Barcode? result;
  QRViewController? controller;

  final environmentSensors = EnvironmentSensors();

  var enableLight = false;

  var hasCameraEnable = false;

  var hasRequested = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    WidgetsBinding.instance.addPostFrameCallback((duration) async {
      var cameraPermission = await Permission.camera.status;
      if(cameraPermission==PermissionStatus.granted||cameraPermission==PermissionStatus.limited){
        setState(() {
          hasCameraEnable = true;
          hasRequested = true;
        });
        _initLight();
      }else{
        var info =  PermissionCenterConfig.permissionMap[Permission.camera];
        if(info['hasSet']==true){
          // print("111111");
          hasRequested = true;
        }else{
          // print("22222");
          hasRequested = false;
        }
      }

    });
  }

  Future<void> _initLight() async {
    var enable = await environmentSensors.getSensorAvailable(SensorType.Light);
    setState(() {
      enableLight = enable;
    });
    if (enableLight) {
      environmentSensors.light.listen((event) {
        if (mounted) {
          Future.delayed(Duration(milliseconds: 200),(){
            if(event<30&&!isFlashOpen){
              _openFlash();
            }
          });
        }
      });
    } else {}
  }

  void reassemble() {
    super.reassemble();
    if (Platform.isAndroid) {
      controller?.pauseCamera();
    } else if (Platform.isIOS) {
      controller?.resumeCamera();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [

          if(!hasCameraEnable)
            Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  CommonText('使用扫一扫扫描长者码、访客码等二维码以及拍照上传工作照片、长者头像、健康档案时，需要申请您的相机权限',textColor: Colors.white),
                  SizedBox(height: 20,),
                  CommonText('去设置',textColor: Colors.white).onTap((){
                    _toRequestCamera();
                  })
                ],
              ),
            ),

          if(hasCameraEnable)
          QRView(
              key: qrKey,
              onQRViewCreated: _onQRViewCreated,
              overlay: QrScannerOverlayShape(
                borderColor: Colors.red,
                borderRadius: 10,
                borderLength: 30,
                borderWidth: 10,
                cutOutSize: 300,
              )),
          SafeArea(
              child: Icon(
            Icons.arrow_back_ios,
            color: Colors.white,
          )
                  .addToContainer(
                      decoration: BoxDecoration(
                          color: Color(0x60000000), shape: BoxShape.circle),
                      width: 45,
                      height: 45,
                      alignment: Alignment.center,
                      margin:
                          EdgeInsets.symmetric(horizontal: 16, vertical: 10))
                  .onTap(() {
            Navigator.pop(context);
          })),
          // if(!enableLight)
          IconButton(
            onPressed: () {
              if(isFlashOpen){
                _closeFlash();
              }else{
                _openFlash();
              }
            },
            icon: Icon(
              Icons.flashlight_on,
              size: 50,
            ),
            color: isFlashOpen?Colors.white:Colors.grey,
          ).setLocation(bottom: 60,left: 0,right: 0)
        ],
      ),
    );
  }

  Future<void> _toRequestCamera() async {

    if(hasRequested){
      ///跳转设置
      await openAppSettings();

    }else{
      var result = await Permission.camera.request();
      if(result==PermissionStatus.granted||result==PermissionStatus.limited){
        setState(() {
          hasCameraEnable = true;
          hasRequested = true;
        });
        _initLight();

      }
      PermissionCenterConfig.savePermissionInit(Permission.camera);
    }
  }

  var isFlashOpen = false;
  void _openFlash(){
   setState(() {
     isFlashOpen = true;
   });
    controller?.toggleFlash();
  }

  void _closeFlash(){
    setState(() {
      isFlashOpen = false;
    });
    controller?.toggleFlash();
  }

  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');

  void _onQRViewCreated(QRViewController controller) {
    this.controller = controller;
    controller.scannedDataStream.listen((scanData) {
      if (mounted && opened) {
        opened = false;
        Navigator.pop(context, scanData.code);
      }
    });
    controller.resumeCamera();
  }

  bool opened = true;

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    controller?.dispose();
    opened = false;
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      Permission.camera.status.then((result){
        if(result==PermissionStatus.granted||result==PermissionStatus.limited){
          setState(() {
            hasCameraEnable = true;
            hasRequested = true;
          });
          _initLight();

        }
      });

    }
  }

}
